import NavBar from '@/components/NavBar'
import {
  avatorChange,
  EditProfile,
  getUserProfile,
  logout,
} from '@/store/actions/profile'
import { List, DatePicker, Drawer, Toast, Modal } from 'antd-mobile'
import classNames from 'classnames'
import dayjs from 'dayjs'
import React, { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import styles from './index.module.scss'

const alert = Modal.alert
const Item = List.Item

export default function ProfileEdit() {
  const dispatch = useDispatch()
  const history = useHistory()
  const userProfile = useSelector((state) => state.profile.userProfile)
  //   console.log(userProfile)
  // 控制全屏抽屉菜单状态
  const [open, setOpen] = useState({
    visible: false,
    type: '',
  })
  // 半屏抽屉
  const [drawerList, setDrawerList] = useState({
    visible: false,
    type: '',
  })
  const onClose = () => {
    setOpen({
      visible: false,
      type: '',
    })
  }
  const onCloseList = () => {
    setDrawerList({
      visible: false,
      type: '',
    })
  }

  // 定义半屏内容控制
  const config = {
    photo: [
      {
        title: '拍照',
        onClick: () => {
          console.log('拍照')
          onCloseList()
        },
      },
      {
        title: '本地相册',
        onClick: () => {
          // console.log('本地相册')
          fileRef.current.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        onClick: () => {
          onCommit('gender', 0)
        },
      },
      {
        title: '女',
        onClick: () => {
          onCommit('gender', 1)
        },
      },
    ],
  }

  const fileRef = useRef(null)

  const changeFile = async (e) => {
    const photo = e.target.files[0]
    console.log(photo)
    // 上传头像用formata对象
    const fd = new FormData()
    fd.append('photo', photo)

    await dispatch(avatorChange(fd))

    Toast.success('头像更换成功', 1)
    onCloseList()
  }
  useEffect(() => {
    dispatch(getUserProfile())
  }, [dispatch])

  // 提交修改内容
  const onCommit = async (type, value) => {
    console.log(type, value)
    await dispatch(
      EditProfile({
        [type]: value,
      })
    )
    Toast.success('修改成功', 1)
    onClose()
    onCloseList()
  }

  // 修改生日
  const onBirthdayChange = (value) => {
    // console.log(value)
    // const year = value.getFullYear()
    // const month = value.getMonth() + 1
    // const date = value.getDate()
    // const dateStr = `${year}-${month}-${date}`
    // console.log(dateStr)

    // 更改数据
    onCommit('birthday', dayjs(value).format('YYYY-MM-DD'))
    // dispatch(EditProfile({ birthday: dateStr }))
  }

  // 退出
  const loginOut = () => {
    alert('温馨提示', '亲,您确定要退出吗?', [
      { text: '取消', onPress: () => console.log('cancel') },
      {
        text: '确定',
        onPress: () => {
          dispatch(logout())
          // 跳转到登录页
          history.push('/login')
          // 提示
          Toast.success('退出登录成功', 1)
        },
      },
    ])
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航 */}
        <NavBar>个人信息</NavBar>

        <div className="wrapper">
          <List className="profile-list">
            <Item
              arrow="horizontal"
              extra={
                <span className="avatar-wrapper">
                  <img src={userProfile.photo} alt="" />
                </span>
              }
              onClick={() => setDrawerList({ visible: true, type: 'photo' })}
            >
              头像
            </Item>
            <Item
              arrow="horizontal"
              onClick={() => {
                setOpen({
                  visible: true,
                  type: 'name',
                })
              }}
              extra={userProfile.name}
            >
              昵称
            </Item>
            <Item
              arrow="horizontal"
              onClick={() => {
                setOpen({
                  visible: true,
                  type: 'intro',
                })
              }}
              extra={
                <span
                  className={classNames(
                    'intro',
                    userProfile.intro ? 'normal' : ''
                  )}
                >
                  {userProfile.intro || '未填写'}
                </span>
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow="horizontal"
              extra={userProfile.gender === 1 ? '女' : '男'}
              onClick={() => setDrawerList({ visible: true, type: 'gender' })}
            >
              性别
            </Item>
            <DatePicker
              mode="date"
              value={new Date(userProfile.birthday)}
              title="选择年月日"
              minDate={new Date(1900, 1, 1, 0, 0, 0)}
              maxDate={new Date()}
              onChange={onBirthdayChange}
            >
              <Item arrow="horizontal">生日</Item>
            </DatePicker>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input type="file" hidden ref={fileRef} onChange={changeFile} />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={loginOut}>
            退出登录
          </button>
        </div>
      </div>
      {/* 全屏表单抽屉 */}
      <Drawer
        position="right"
        className="drawer"
        style={{ minHeight: document.documentElement.clientHeight }}
        children={''}
        open={open.visible}
        sidebar={
          open.visible && (
            <EditInput
              onClose={onClose}
              type={open.type}
              onCommit={onCommit}
              visible={open.visible}
            ></EditInput>
          )
        }
      />

      {/* 菜单抽屉 */}
      <Drawer
        onOpenChange={onCloseList}
        position="bottom"
        className="drawer-list"
        children={''}
        open={drawerList.visible}
        sidebar={
          drawerList.visible && (
            <EditList
              type={drawerList.type}
              config={config}
              onCloseList={onCloseList}
            ></EditList>
          )
        }
      />
    </div>
  )
}
